<template>
  <div class="c-p c-bg-sgray" v-if="agentProfitInfo != null">
    <div class="c-hh300 c-text-hidden c-pa c-w100">
      <img :src="$addXossFilter(userHeadImg ? userHeadImg : require('@/assets/defult_head.png'))" class="c-w100 top-img" alt="">
      <div class="c-w100 c-h c-pa c-p-t0 c-p-l0 glass c-translucent-balck60 c-pz7">
        <div class="c-w100 c-h backdropFilter2"></div>
      </div>
    </div>
    <div class="c-pt30 c-p c-pz9">
      <div class="c-flex-row c-mh24">
        <img class="c-ww120 c-hh120 c-brp50 bd1-white" :src="$addXossFilter(userHeadImg ? userHeadImg : require('@/assets/defult_head.png'))" alt="">
        <div class="c-flex-column c-justify-sb c-w0 c-flex-grow1 c-ml20 c-pv4">
          <template v-if="type == 1 && agentUserInfo != null">
            <div class="c-flex-row c-aligni-center">
              <span class="c-fs28 c-fc-white">{{agentUserInfo.nickname && agentUserInfo.nickname.length > 6 ? (agentUserInfo.nickname.substring(0, 6) + '...') : agentUserInfo.nickname}}</span>
              <identity-com class="c-pl10" :vipType="agentUserInfo.vipType"></identity-com>
            </div>
            <div class="c-fs24 c-fc-white c-flex-row c-aligni-center" @click="handleClickMyTeamList">
              <span>员工数：{{agentProfitInfo.staffNum}}人</span>
              <i class="iconfont c-ml4 c-fs22">&#xe635;</i>
            </div>
          </template>
          <template v-else>
            <div class="c-fs28 c-fc-white">{{staffInfo.nickname}}（ID号：{{staffInfo.userId}}）</div>
            <div class="c-fs24 c-fc-white"><span class="c-mr40">归属于：{{staffInfo.aNickname}}</span><span class="">推广收益：{{staffInfo.staffRatio}}%</span></div>
          </template>
        </div>
      </div>
      <div class="c-bg-white c-br16 c-pv32 c-ph40 c-flex-row c-justify-sb c-mt30 c-mh24">
        <template v-if="type == 1">
          <div class="c-w100 c-flex-row c-justify-sb" @click.stop="handleClickStaffDetail">
            <div class="c-flex-column c-aligni-start">
              <div class="c-flex-column c-aligni-start">
                <div class="c-fs24 c-fc-gray">累计消耗额度(元)</div>
                <div class="c-fs28 c-fc-xblack c-mt8 c-fw600">{{agentProfitInfo.totalMoney ? agentProfitInfo.totalMoney : 0}}</div>
              </div>
              <div class="c-flex-column c-aligni-start c-mt20">
                <div class="c-fs24 c-fc-gray">本月消耗额度(元)</div>
                <div class="c-fs28 c-fc-xblack c-mt8 c-fw600">{{agentProfitInfo.nowMonthPayMoney ? agentProfitInfo.nowMonthPayMoney : 0}}</div>
              </div>
            </div>
            <div class="c-flex-column c-aligni-start">
              <div class="c-flex-column c-aligni-start">
                <div class="c-fs24 c-fc-gray">剩余额度(元)</div>
                <div class="c-fs28 c-fc-xblack c-mt8 c-fw600">{{agentProfitInfo.moneyRemainingQuota ? agentProfitInfo.moneyRemainingQuota : 0}}</div>
              </div>
              <div class="c-flex-column c-aligni-start c-mt20">
                <div class="c-fs24 c-fc-gray">本月收益(元)</div>
                <div class="c-fs28 c-fc-xblack c-mt8 c-fw600">{{agentProfitInfo.nowMonthIncome ? agentProfitInfo.nowMonthIncome: 0}}</div>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="c-flex-column c-aligni-start">
            <div class="c-flex-column c-aligni-start" @click="goIncome">
              <div class="c-fs24 c-fc-gray">本月消耗额度(元)</div>
              <div class="c-fs28 c-fc-xblack c-mt8 c-fw600">{{staffInfo.payMoney ? staffInfo.payMoney : 0}}</div>
            </div>
            <div class="c-flex-column c-aligni-start c-mt20" @click="goIncome">
              <div class="c-fs24 c-fc-gray">本月收益(元)</div>
              <div class="c-fs28 c-fc-xblack c-mt8 c-fw600">{{staffInfo.staffIncome ? staffInfo.staffIncome : 0}}</div>
            </div>
          </div>
          <div class="c-flex-column c-aligni-start">
            <div class="c-flex-column c-aligni-start" @click="goIncome">
              <div class="c-fs24 c-fc-gray">本月消耗名额(个)</div>
              <div class="c-fs28 c-fc-xblack c-mt8 c-fw600">{{staffInfo.quota ? Number(staffInfo.quota).toFixed(0) : 0}}</div>
            </div>
            <div class="c-flex-column c-aligni-start c-mt20" @click="goCustomerManage">
              <div class="c-fs24 c-fc-gray">累计直推用户(人)</div>
              <div class="c-fs28 c-fc-xblack c-mt8 c-fw600">{{staffInfo.staffNum ? staffInfo.staffNum: 0}}</div>
            </div>
          </div>
        </template>
      </div>
      <template v-if="tabList.length > 0">
        <new-search-bar class="c-mt16" :bgSearch="'c-bg-sgray'" :bgInput="'c-bg-white'" :searchText="searchText" @search="startSearch" @cancel="startSearch"></new-search-bar>
        <div class="c-flex-row c-aligni-center c-mh24">
          <div class="c-w0 c-flex-grow1">
            <my-small-tabbar ref="smallTab" :isScroll="true" :flexClass="''" :tabNameClass="'c-fs24'" :tabList="tabList" :tabIndex="typeBar" :tabHeight="'64'" @changeTab="changeType"></my-small-tabbar>
          </div>
          <div class="c-pl12">
            <div class="iconfont c-fs20 c-fc-gray" :class="popupShow ? 'c-rotate180' : ''" @click.stop="handleClickChoose">&#xe6a9;</div>
          </div>
        </div>
        <div class="c-ph24">
          <div class="c-flex-row c-ph20 c-pv20 c-br15 c-bg-white c-mt20" v-for="(item, index) in agentProdList" :key="index" @click.stop="handleClickDetail(item)">
            <div class="c-ww150 c-hh100 c-text-hidden c-br12">
              <vip-custom-img :coverUrl="item.cover" :cover="item.prodType == cfrom.vip || item.prodType == cfrom.svip ? item.cover : {}" :imgClass="'imgCloseBig c-br12'" :fontClass="{
                boxStyle: 'c-pv20 c-pl12',
                name: 'c-fs24 c-text-ellipsis1 c-fw-b',
                duration: 'c-fs18'}" :content="{name: item.name, duration: item.duration, durationType: item.durationType}" />
            </div>
            <div class="c-flex-column c-justify-sb c-w0 c-flex-grow1 c-ml20">
              <div class="c-fs24 c-fc-xblack c-text-ellipsis1">{{item.name}}</div>
              <div class="c-flex-row c-aligni-end c-justify-sb">
                <div class="c-fs24 c-fc-xmlred">{{'￥' | iosPriceFilter}}{{item.price | moneyStr}}</div>
                <div class="c-fs20 c-fc-white c-ww120 c-hh44 c-flex-row c-flex-center c-br24 theme-bg" @click.stop="goSpreadInvite(item)">推广</div>
              </div>
            </div>
          </div>
          <loading-status-tem
            :dataStatus="dataStatus"
            noDataText="暂无结果"
            class="c-bg-sgray"
          ></loading-status-tem>
        </div>
      </template>
      <popup-picker v-model="choosePrimary" :show="popupShow" :themeColor="$getThemeColor()" class="selectPicker hide" title="" style="c-w100" :data="chooseList" @on-change="changeSelect" @on-show="showPicker" @on-hide="hidePicker"></popup-picker>
    </div>
  </div>
</template>

<script>
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import { PopupPicker } from 'ckjrweb-mp-ui/src/components/index';
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import VipCustomImg from "@/components/templates/common/VipCustomImg.vue";
import identityCom from "@/components/templates/common/identityCom.vue";
import { goDetails } from "@/utils/goDetails.js"
import { utilJs } from "@/utils/common.js"
export default {
  name: 'StaffIndex',
  components: {
    PopupPicker,
    newSearchBar,
    MySmallTabbar,
    loadingStatusTem,
    VipCustomImg,
    identityCom
  },
  data() {
    return {
      LIMIT: 10,
      pageIndex: 0,
      page: 1,
      showModal: false,
      searchText: '',
      tabList: [],
      tabListArray: [],
      typeBar: 0,
      staffInfo: '',
      prodType: '',
      dataStatus: 'HAS_MORE_DATA',
      agentProdList: [],
      cfrom: global.ckFrom,
      popupShow: false,
      chooseList: [],
      choosePrimary: [],
      agentProfitInfo: null,
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      userHeadImg: localStorage.getItem("userHeadImg"),
      type: 0, // 判断是从金额管理页面进来的
      agentUserInfo: null,
    }
  },
  created() {
    utilJs.appShare(this);
  },
  watch: {
    $route(to, from) {
      if (from.path == "/") {
        this.initActivated();
      }
    }
  },
  methods: {
    initActivated() {
      this.showModal = false;
      this.searchText = '';
      this.promotedAccountList = [];
      this.tabList = [];
      this.tabListArray = [];
      this.typeBar = 0;
      this.prodType = '';
      this.popupShow = false;
      this.chooseList = [];
      this.choosePrimary = [];
      this.agentProfitInfo = null;
      this.agentUserInfo = null;
      this.getTabList();
      this.getAgentProfitInfo();
    },
    handleClickDetail(item) {
      let courseType = item.prodType == 110 ? 0 : item.prodType == 111 ? 1 : item.prodType == 112 ? 2 : '';
      let prodType = item.prodType;
      if (item.prodType == 110 || item.prodType == 111 || item.prodType == 112) {
        prodType = global.ckFrom.course;
      } else if (item.prodType == 117) {
        prodType = global.ckFrom.edu;
      } else if (item.prodType == global.ckFrom.giftCard) {
        // 小程序环境不能跳充值页面
        if (this.$isWxApp()) {
          return
        }
        this.$routerGo(this, 'push', {
          path: '/member/giftCard/rechargeCard'
        })
      }
      goDetails(this, prodType, item.prodId, '', courseType);
    },
    goSpreadInvite(item) {
      let courseType = item.prodType == 110 ? 0 : item.prodType == 111 ? 1 : item.prodType == 112 ? 2 : '';
      let ckFrom = item.prodType;
      if (item.prodType == 110 || item.prodType == 111 || item.prodType == 112) {
        ckFrom = global.ckFrom.course;
      }
      if (item.prodType == global.ckFrom.datum || item.prodType == global.ckFrom.itemBank || item.prodType == global.ckFrom.edu || item.prodType == global.ckFrom.testpPaper || item.prodType == global.ckFrom.word) {
        goDetails(this, item.prodType, item.prodId, '', courseType);
      } else if (item.prodType == global.ckFrom.giftCard) {
        // 小程序环境不能跳充值页面
        if (this.$isWxApp()) {
          return
        }
        this.$routerGo(this, 'push', {
          path: '/member/giftCard/rechargeCard'
        })
      } else {
        this.$routerGo(this, "push", {
          path: "/homePage/spread/spreadCustom",
          query: { cId: item.prodId, extId: item.prodId, ckFrom: ckFrom, promote: 1, courseType: courseType }
        });
      }
    },
    handleClickStaffDetail() {
      this.$routerGo(this, "push", { path: "/homePage/agent/staffDetail", query: {'type': 2, isAgent: 1} });
    },
    handleClickMyTeamList() {
      this.$routerGo(this, 'push', {
        path: '/homePage/agent/myTeamList',
        query: {
          type: 3
        }
      })
    },
    showPicker() {
      this.popupShow = true;
    },
    hidePicker() {
      this.popupShow = false;
    },
    handleClickChoose() {
      this.popupShow = true;
    },
    changeSelect(value) {
      let valueString = value.join();
      this.tabListArray.forEach((ele) => {
        if (ele.title == valueString) {
          this.prodType = ele.prodType;
          this.typeBar = ele.index;
          this.$refs.smallTab.scrollPosition(ele.index);
          return;
        }
      })
      this.pageIndex = 0;
      this.page = 1;
      this.agentProdList = [];
      this.getAgentProdList();
    },
    initData() {
      this.LIMIT = 10;
      this.pageIndex = 0;
      this.page = 1;
      this.searchText = '';
      this.dataStatus = 'HAS_MORE_DATA';
      this.agentProdList = [];
      this.getAgentProdList();
    },
    changeType(type) {
      this.choosePrimary = [];
      this.choosePrimary.push(this.tabListArray[type].title);
      this.typeBar = type;
      this.prodType = this.tabListArray[type].prodType;
      this.pageIndex = 0;
      this.page = 1;
      this.dataStatus = 'HAS_MORE_DATA';
      this.agentProdList = [];
      this.getAgentProdList();
    },
    startSearch(e) {
      this.pageIndex = 0;
      this.page = 1;
      this.agentProdList = [];
      this.searchText = e.searchValue;
      this.getAgentProdList();
    },
    goMicroPage(mId) {
      this.$routerGo(this, "push", { path: "/homePage/microPage/microPage", query: {'mId': mId, 'isPromotedAccount': 1} });
    },
    goIncome() {
      this.$routerGo(this, "push", { path: "/homePage/agent/staffDetail", query: {'type': 2} });
    },
    goCustomerManage() {
      this.$routerGo(this, "push", { path: "/homePage/agent/staffDetail", query: {'type': 1} });
    },
    getStaffInfo() {
      utilJs.getMethod(`${global.apiurl}Agent/staffInfo`, res => {
        if (res && res.isStaff != 1) {
          this.$routerGo(this, "replace", { path: "/" });
        }
        this.staffInfo = res;
      });
    },
    getAgentProfitInfo() {
      utilJs.getMethod(`${global.apiurl}Agent/agentProfitInfo`, res => {
        this.agentProfitInfo = res;
        this.agentUserInfo = res.userInfo;
      })
    },
    getTabList() {
      utilJs.getMethod(`${global.apiurl}Agent/tabList`, res => {
        if (res) {
          let listArray = [];
          let chooseListArray = []
          res.forEach((ele, index) => {
            if (ele.enableShow == 1) {
              let obj = {
                index: index,
                enableShow: ele.enableShow,
                title: ele.name,
                prodType: ele.prodType
              }
              listArray.push(obj);
              chooseListArray.push(ele.name);
            }
          })
          this.tabListArray = listArray;
          this.chooseList.push(chooseListArray);
          this.tabList = listArray;
          this.prodType = this.tabListArray[0].prodType;
          this.initData();
        }
      })
    },
    getAgentProdList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(`${global.apiurl}Agent/getAgentProdList?searchName=${this.searchText}&index=${this.pageIndex}&page=${this.page}&limit=${this.LIMIT}&prodType=${this.prodType}`, res => {
        if (this.page == 1) {
          this.agentProdList = res.data;
        } else {
          this.agentProdList = [...this.agentProdList, ...res.data];
        }
        if (res.data && (res.data.length < this.LIMIT)) {
          this.dataStatus = this.page == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          this.pageIndex += this.LIMIT;
          this.page++;
        }
      }, fileRes => {
        this.dataStatus = "DATA_ERROR"
      })
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.agentProdList.length > 0) {
          this.getAgentProdList();
        }
      });
    },
    //分享
    wechatShare: function () {
      let title = this.type == 1 ? "金额管理" : '我是员工';
      let shareUrl = '';
      if (this.type == 1) {
        shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}&type=1`;
      } else {
        shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      }
      utilJs.wechatConfig(shareUrl, title, "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      let title = this.type == 1 ? "金额管理" : '我是员工';
      let shareUrl = '';
      if (this.type == 1) {
        shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}&type=1`;
      } else {
        shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      }
      utilJs.appShareTrue(title, "", shareUrl, "");
    }
  },
  activated() {
    this.type = this.$route.query.type || 0;
    if (utilJs.checkNeedInitData(this.agentProdList)) {
      this.initActivated();
    }
    if (this.type == 1) {
      let url = 'members/agentApplyPage';
      utilJs.getMethod(global.apiurl + url, res => {
        let amountManagementName = res && res.agentConf && res.agentConf.amountManagementName ? res.agentConf.amountManagementName : '金额管理';
        setDocumentTitle(amountManagementName);// eslint-disable-line
      })
    } else {
      this.getStaffInfo();
      setDocumentTitle("我是员工");// eslint-disable-line
    }
    this.wechatShare();
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.staff-page-bg {
  background-image: linear-gradient(180deg, #3B457B 0%, #2B325C 100%);
}
.staff-content-bg {
  width: 100%;
  height: 19.6rem;
  padding-top: 5.2rem;
  background: url('../../../assets/i/wap/newAreaAgent/inviteStaff.png') no-repeat left top;
  background-size: 100% 100%;
}
.fc-B38E5B {
  color: #B38E5B;
}
.fc-330000 {
  color: #330000;
}
.dialog-demo /deep/ .weui-dialog {
  border-radius: 0.5rem;
}
.bg-top {
  background: rgba(0, 0, 0, 0.5);
}
.top-img {
  min-height: 7.5rem;
  /* filter: blur(2px); */
}
.bd1-white {
  border: 1px solid #fff;
}
.glass {
  background-image: url("../../../assets/i/wap/datum/glass.png");
}
.backdropFilter2 {
  backdrop-filter: blur(3px);
}
</style>